package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.api.content.model.CourseBaseDTO;
import com.xuecheng.api.content.model.TeachplanDTO;
import com.xuecheng.api.content.model.dto.CourseTeacherDTO;
import com.xuecheng.common.domain.code.CommonErrorCode;
import com.xuecheng.common.enums.common.CommonEnum;
import com.xuecheng.common.enums.content.CourseAuditEnum;
import com.xuecheng.common.enums.content.TeachPlanEnum;
import com.xuecheng.common.exception.ExceptionCast;
import com.xuecheng.content.common.constant.ContentErrorCode;
import com.xuecheng.content.common.util.QiniuUtils;
import com.xuecheng.content.convert.CourseBaseConvert;
import com.xuecheng.content.convert.CourseTeacherConvert;
import com.xuecheng.content.convert.TeachplanConvert;
import com.xuecheng.content.entity.CourseBase;
import com.xuecheng.content.entity.CourseMarket;
import com.xuecheng.content.entity.CourseTeacher;
import com.xuecheng.content.entity.Teachplan;
import com.xuecheng.content.mapper.CourseTeacherMapper;
import com.xuecheng.content.mapper.TeachplanMapper;
import com.xuecheng.content.service.CourseBaseService;
import com.xuecheng.content.service.CourseTeacherService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 课程-教师关系表 服务实现类
 * </p>
 *
 * @author itcast
 */
@Slf4j
@Service
public class CourseTeacherServiceImpl extends ServiceImpl<CourseTeacherMapper, CourseTeacher> implements CourseTeacherService {
    @Autowired
    private CourseBaseService courseBaseService;
    @Autowired
    private CourseTeacherMapper courseTeacherMapper;

    @Override
    public List<CourseTeacherDTO> getCourseTeacherByCourseId(Long courseBaseId, Long companyId) {

        if (ObjectUtils.isEmpty(courseBaseId) || ObjectUtils.isEmpty(companyId)) {
            ExceptionCast.cast(ContentErrorCode.E_120024);
        }
        //判断课程是否存在
        CourseBaseDTO baseDTO = courseBaseService.getCourseBaseById(courseBaseId, companyId);

        LambdaQueryWrapper<CourseTeacher> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CourseTeacher::getCourseId, courseBaseId);
        List<CourseTeacher> list = list(queryWrapper);
        List<CourseTeacherDTO> dtoList = CourseTeacherConvert.INSTANCE.entitys2dtos(list);
        return dtoList;
    }

    /**
     * 添加修改教师
     * @param dto
     * @return
     */
    @Override
    @Transactional
    public CourseTeacherDTO createOrModifyCourseTeachr(CourseTeacherDTO dto,Long companyId) {
        if (ObjectUtils.isEmpty(companyId)||
                ObjectUtils.isEmpty(dto.getPhotograph())||
                ObjectUtils.isEmpty(dto.getPosition())||
                ObjectUtils.isEmpty(dto.getTeacherName())
        ){
            ExceptionCast.cast(CommonErrorCode.E_100101);
        }
        CourseTeacherDTO  resultDTO=null;
        if (ObjectUtils.isEmpty(dto.getCourseTeacherId())){
            //添加
            resultDTO = createCourseTeacher(dto,companyId);

        }else {
            //修改
            resultDTO =  modifyCourseTeacher(dto,companyId);
        }

        return resultDTO;
    }

    @Override
    @Transactional
    public Boolean removeCourseTeachr(Long courseId, Long courseTeacherId, Long companyId) {
        if (ObjectUtils.isEmpty(courseId)||ObjectUtils.isEmpty(courseTeacherId)){
            ExceptionCast.cast(ContentErrorCode.E_1200501);
        }
        //判断课程状态
        CourseBase courseBase = courseBaseService.getCourseBaseByBaseId(courseId, companyId);
        String status = courseBase.getAuditStatus();
        if (CourseAuditEnum.AUDIT_PASTED_STATUS.getCode().equals(status)||
                CourseAuditEnum.AUDIT_PUBLISHED_STATUS.getCode().equals(status)||
                CourseAuditEnum.AUDIT_COMMIT_STATUS.getCode().equals(status)){
            throw new RuntimeException("课程下架后，才可以删除，课程状态异常");
        }
        if (CommonEnum.DELETE_FLAG.getCode().equals(courseBase.getStatus().toString())){
            throw new RuntimeException("课程已经删除！！！");
        }
        //判断此教师是否此课程
        LambdaQueryWrapper<CourseTeacher> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CourseTeacher::getCourseId,courseId);
        queryWrapper.eq(CourseTeacher::getId,courseTeacherId);
        CourseTeacher one = getOne(queryWrapper);
        if (ObjectUtils.isEmpty(one)){
            ExceptionCast.cast(ContentErrorCode.E_1200504);
        }
        LambdaUpdateWrapper<CourseTeacher> wrapper = Wrappers.lambdaUpdate();
        wrapper.eq(CourseTeacher::getId,courseTeacherId);
        int delete = courseTeacherMapper.delete(wrapper);
        if (delete<1){
            throw new RuntimeException("删除课程失败!!");
        }
        return true;
    }

    private CourseTeacherDTO modifyCourseTeacher(CourseTeacherDTO dto,Long companyId) {
        //课程教师信息不存在

        CourseBaseDTO BaseDTO = courseBaseService.getCourseBaseById(dto.getCourseId(), companyId);
        //查询教师信息是否否存在
        LambdaQueryWrapper<CourseBase> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CourseBase::getId, dto.getCourseId());
        int count = courseBaseService.count(queryWrapper);
        if (count < 1) {
            ExceptionCast.cast(ContentErrorCode.E_120402);
        }
        CourseTeacher teacher = getById(dto.getCourseTeacherId());
        if (!teacher.getTeacherName().equals(dto.getTeacherName())){
            CourseTeacher ct=getCourseTeacherByTeacherName(dto.getTeacherName());
            if (!ObjectUtils.isEmpty(ct)){
                ExceptionCast.cast(ContentErrorCode.E_1200502);
            }
        }
        LambdaUpdateWrapper<CourseTeacher> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(CourseTeacher::getId,dto.getCourseTeacherId());
        updateWrapper.set(CourseTeacher::getCoursePubId, dto.getCoursePubId());
        updateWrapper.set(CourseTeacher::getIntroduction, dto.getIntroduction());
        updateWrapper.set(CourseTeacher::getPhotograph,dto.getPhotograph());
        updateWrapper.set(CourseTeacher::getPosition,dto.getPosition());
        updateWrapper.set(CourseTeacher::getTeacherName,dto.getTeacherName());
        // 4.判断修改后的结果
        boolean result = this.update(updateWrapper);
        if (!result) {
            ExceptionCast.cast(ContentErrorCode.E_1200501);
        }
        // 5.将数据库最新的数据转为dto并返回
        CourseTeacher po = this.getById(dto.getCourseTeacherId());
        CourseTeacherDTO resultDTO = CourseTeacherConvert.INSTANCE.entity2dTo(po);
        return resultDTO;
    }

    private CourseTeacherDTO createCourseTeacher(CourseTeacherDTO dto,Long companyId) {

        // 2.判断业务数据
        //     课程基础信息
        //         判断是否存在
        //         判断是否是同一家教学机构
        //         判断是否删除
        //         判断审核状态：未提交、审核未通过
        CourseBaseDTO courseBase = courseBaseService.getCourseBaseById(dto.getCourseId(), companyId);

        String auditStatus = courseBase.getAuditStatus();
        if (CourseAuditEnum.AUDIT_PASTED_STATUS.getCode().equals(auditStatus)||
                CourseAuditEnum.AUDIT_COMMIT_STATUS.getCode().equals(auditStatus)||
                CourseAuditEnum.AUDIT_PUBLISHED_STATUS.getCode().equals(auditStatus)
        ) {
            ExceptionCast.cast(ContentErrorCode.E_120015);
        }
        //课程不能填写相同名称的教师信息
            CourseTeacher ct=getCourseTeacherByTeacherName(dto.getTeacherName());
        if (!ObjectUtils.isEmpty(ct)){
            ExceptionCast.cast(ContentErrorCode.E_1200502);
        }
        // 4.将dto转为po并保存到数据库中
        CourseTeacher courseTeacher = CourseTeacherConvert.INSTANCE.dTo2entity(dto);
        boolean result = this.save(courseTeacher);
        //     判断保存后的结果
        if (!result) {
            ExceptionCast.cast(ContentErrorCode.E_1200501);
        }


        // 5.将数据库最新的数据转为dto并返回
        CourseTeacher po = this.getById(courseTeacher.getId());

        CourseTeacherDTO teacherDTO = CourseTeacherConvert.INSTANCE.entity2dTo(po);

        return teacherDTO;
    }

    private CourseTeacher getCourseTeacherByTeacherName(String teacherName) {
        LambdaQueryWrapper<CourseTeacher> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CourseTeacher::getTeacherName,teacherName);
        CourseTeacher one = getOne(queryWrapper);
        if (ObjectUtils.isEmpty(one)){
            return null;
        }else {
            return one;
        }

    }
}
